define(function(require, exports, module) {

	var layer = require("layer");
	var cookieSetting = require("cookieSetting");

	// 开始进度遮罩
	var processLayerIndex = -1;
	var showProcess = function() {
		processLayerIndex = layer.load(0, {
			shade: [0.4, '#fafafa']
		}); //打开loading
	}

	// 关闭进度遮罩
	var closeProcess = function() {
		if (processLayerIndex != -1) {
			layer.close(processLayerIndex);
		}
	}

	// 字符为空判断
	var isEmpty = function(str) {
		return !(str != "" && str != null);
	}

	// confirm对话框
	var confirm = function(content, okFunction, cancelFunction) {
		var options = {
			confirmButton: "确定",
			cancelButton: "取消",
			content: content,
			closeOnClick: false,
			confirm: function() {
				if ($.isFunction(okFunction)) {
					okFunction();
				}
				//myConfirm.close();
			},
			cancel: function() {
				if ($.isFunction(cancelFunction)) {
					cancelFunction();
				}
				//myConfirm.close();
			},
			onCloseComplete: function() {
				myConfirm.destroy();
			}
		};
		var myConfirm = new jBox('Confirm', options);
		myConfirm.open();
	}


	// alert对话框
	var alert = function(messasge, okFunction) {
		if (!isEmpty(messasge)) {
			$("#alertModal").find(".modal-body").text(messasge);
		}
		$("#alertOkBtn").unbind('click');
		$("#alertOkBtn").click(function() {
			if ($.isFunction(okFunction)) {
				okFunction();
			}
			$("#alertModal").find(".modal-body").html("");
		});
		$("#alertModal").modal({
			backdrop: 'static',
			keyboard: false
		});
	}

	// BS Alert 信息框
	// type: 1--success, 2--info, 3--warning, 4--danger
	var bsAlert = function(content, type) {
		var alertStr = "<div id='bsAlert' class='alert'><a href='#'' class='close' data-dismiss='alert'>&times;</a></div>";
		var icon = "<i class='fa fa-check-circle'></i>";
		$('.breadcrumb').after(alertStr);
		switch (type) {
			case 2:
				$("#bsAlert").addClass('alert-info');
				icon = "<i class='fa fa-info-circle'></i>";
				break;
			case 3:
				$("#bsAlert").addClass('alert-warning');
				icon = "<i class='fa fa-exclamation-triangle'></i>";
				break;
			case 4:
				$("#bsAlert").addClass('alert-danger');
				icon = "<i class='fa fa-times-circle'></i>";
				break;
			default:
				$("#bsAlert").addClass('alert-success');
				icon = "<i class='fa fa-check-circle'></i>";
				break;
		}
		$("#bsAlert").append(icon);
		$("#bsAlert").append(" ");
		$("#bsAlert").append(content);
	}

	// 模拟弹出窗口
	var showModal = function(title, url, width, initFunction, okFunction, closeFunction) {
		var modalWidth = 700;
		if (width != null) modalWidth = width;
		var myModal = null;
		var jBoxId = newGuid();
		var options = {
			id: jBoxId,
			title: title,
			width: modalWidth,
			maxHeight: getMaxHeight(),
			minHeight: 400,
			closeOnClick: false,
			draggable: 'title',
			dragwrapper: false,
			confirmButton: "保存",
			closeButton: 'title',
			fade: true,
			animation: 'zoomOut',
			//zIndex : jBox.zIndexMax ? Math.max(jBox.zIndexMax, 10001) : 10001,
			ajax: {
				url: url,
				reload: true,
				setContent: true,
				spinner: true,
				complete: function() {
					if ($.isFunction(initFunction)) {
						initFunction(myModal);
					}
				}
			},
			onClose: function() {
			},
			onCloseComplete: function() {
				if ($.isFunction(closeFunction)) {
					closeFunction(myModal.options.returnValue);
				}
				myModal.destroy();
			}
		};
		myModal = new jBox('Modal', options);
		myModal.open();
	}

	// ajax submitForm
	var submitForm = function(form, callBack, dataType) {
		var options = {
			type: 'post',
			dataType: dataType || 'json',
			success: function() {
				if ($.isFunction(callback)) {
					callback(data);
				}
				closeProcess();
			},
			error: function(response, textStatus, errorThrown) {
				try {
					closeProcess();
					var data = $.parseJSON(response.responseText);
					//检查登录
					/*if(!YiYa.checkLogin(data)){
					 			return false;
					 		}else{
						 		YiYa.alert('提示', data.msg || "请求出现异常,请联系管理员",'error');
						 	}*/
				} catch (e) {
					bsAlert('提示', "请求出现异常,请联系管理员.", 4);
				}
			},
			complete: function() {}
		};
		ajaxSubmit(form, option);
	}

	// Ajax 提交
	var ajaxSubmit = function(form, option) {
		form.ajaxSubmit(option);
	}

	// ajax 提交json
	var ajaxJson = function(url, option, callback) {
		$.ajax(url, {
			type: 'post',
			dataType: 'json',
			data: option,
			success: function(data) {
				//坚持登录
				//		 		if(!YiYa.checkLogin(data)){
				//		 			return false;
				//		 		}
				if ($.isFunction(callback)) {
					callback(data);
				}
			},
			error: function(response, textStatus, errorThrown) {
				try {
					closeProcess();
					var data = $.parseJSON(response.responseText);
					//检查登录
					/*if (!YiYa.checkLogin(data)) {
					 			return false;
					 		}else{
						 		YiYa.alert('提示', data.msg || "请求出现异常,请联系管理员",'error');
						 	}*/
				} catch (e) {
					bsAlert('提示', "请求出现异常,请联系管理员.", 4);
				}
			},
			complete: function() {}
		});
	}

	var handleSubmit = function(form, _rules, _messages) {
		var messages = !_messages ? {} : _messages;
		form.validate({
			errorElement : 'span',
            errorClass : 'help-block',
            focusInvalid : false,
            rules : _rules,
            messages : messages,
            highlight : function(element) {
                $(element).closest('.form-group').addClass('has-error');
            },
            success : function(label) {
                label.closest('.form-group').removeClass('has-error');
                label.remove();
            },
            errorPlacement : function(error, element) {
            	var parentDiv = element.parent('div');
            	if (parentDiv.hasClass('input-group')) {
            		parentDiv = parentDiv.parent('div');
            	}
                parentDiv.after(error);
            },
            submitHandler : function(form) {
                form.submit();
            }
		});
	}

	// 生成GRUID
	var guidIndex = 0
	var newGuid = function() {
		var guid = "";
		for (var i = 1; i <= 32; i++) {
			var n = Math.floor(Math.random() * 16.0).toString(16);
			guid += n;
			if ((i == 8) || (i == 12) || (i == 16) || (i == 20))
				guid += "-";
		}
		return leftZeroPad(guidIndex++, 8) + "-" + guid;
	}

	var ajaxGetPage = function(href, data) {
		var userSetting = cookieSetting.getSetting();
		var reg = /javascript|[^\w]/
		if (href && reg.test(href)) { //判断是否合法
			showProcess();
			$(".main_content").hide();
			$.get(href, data, function(res) {
				$(".main_content").html(res);
				if (userSetting.breadcrumb) {
					$(".breadcrumb").addClass("breadcrumb_fixed");
					$(".main_content").show();
				}
				closeProcess();
				$(".main_content").show();
			}, 'html');
			/*
			$(".main_content").load(href, function(response, status, xhr) { //ajax页面加载
				closeProcess();
				if(status == "success" || status == "notmodified") {
					if (userSetting.breadcrumb) {
						$(".breadcrumb").addClass("breadcrumb_fixed");
					}
				} else {
					bsAlert("页面加载失败。", 4);
				}
				$(".main_content").show();
			});
*/
		}
	}

	var ajaxLoadPage = function(href) {
		var userSetting = cookieSetting.getSetting();
		var reg = /javascript|[^\w]/
		if (href && reg.test(href)) { //判断是否合法
			//var index = layer.load(0, {shade: [0.4,'#fafafa']}); //打开loading
			showProcess();
			$(".main_content").hide();
			$(".main_content").load(href, function(response, status, xhr) { //ajax页面加载
				//layer.close(index); //关闭loading
				closeProcess();
				if(status == "success" || status == "notmodified") {
					// response 是响应(返回)的原始文本数据
    				// status 可能是 "success"、 "notmodified"、 "error"、 "timeout"、 "abort"或"parsererror"中的一个
				    // xhr 是经过jQuery封装的XMLHttpRequest对象(保留其本身的所有属性和方法)
					if (userSetting.breadcrumb) {
						$(".breadcrumb").addClass("breadcrumb_fixed");
					}
				} else {
					bsAlert("页面加载失败。", 4);
				}
				$(".main_content").show();
			});
		}
	}

	// 取得弹窗最大高度
	var getMaxHeight = function() {
		return $(window).height() - 150;
	}

	//	数字前补0操作
	var MANY_ZEROS = "000000000000000000";
	var leftZeroPad = function(val, minLength) {
		if (typeof(val) != "string")
			val = String(val);
		return (MANY_ZEROS.substring(0, minLength - val.length)) + val;
	}

	return {
		showProcess: showProcess, // 开始进度遮罩
		closeProcess: closeProcess, // 关闭进度遮罩
		showModal: showModal,
		confirm: confirm,
		alert: alert,
		guid: newGuid,
		bsAlert: bsAlert,
		handleSubmit : handleSubmit,
		ajaxLoadPage : ajaxLoadPage,
		ajaxGetPage : ajaxGetPage
	}
});


/*
	var confirm = function(content, okFunction, cancelFunction) {
		if (!isEmpty(content)) {
			$("#confirmModal").find(".modal-body").text(content);
		}
		if (okFunction != null && typeof(okFunction) == "function") {
			$("#confirmOkBtn").unbind('click');
			$("#confirmOkBtn").click(function() {
				okFunction();
			});
		}
		$("#confirmCnlBtn").unbind('click');
		$("#confirmCnlBtn").click(function() {
			if (cancelFunction != null && typeof(cancelFunction) == "function") {
				cancelFunction();
			}
			$("#confirmModal").find(".modal-body").html("");
		});
		$("#confirmModal").modal({
			backdrop: 'static',
			keyboard: false
		});
	}
	// BS Modal弹窗
	var showModal = function(title, url, okBtnName, okFunction, cancelBtnName, cancelFunction) {
		if (!isEmpty(title)) {
			$("#modal").find("h4.modal-title").text(title);
		}
		if (!isEmpty(okBtnName)) {
			$("#modalOkBtn").text(okBtnName);
		}
		if (!isEmpty(cancelBtnName)) {
			$("#modalCnlBtn").text(cancelBtnName);
		}
		if (okFunction != null && typeof(okFunction) == "function") {
			$("#modalOkBtn").unbind('click');
			$("#modalOkBtn").click(function() {
				okFunction();
			});
		}
		$("#modalCnlBtn").unbind('click');
		$("#modalCnlBtn").click(function() {
			if (cancelFunction != null && typeof(cancelFunction) == "function") {
				cancelFunction();
			}
			$("#modal").find(".modal-body").html("");
		});
		$("#modal").modal({backdrop: 'static', keyboard: false}).on('shown.bs.modal', function (e) {
		  	$("#modal").find(".modal-body").load(url, function(response, status, xhr) {
		  	}).on('hide.bs.modal', function(e) {alert("ok")});
		});
	}

			// BS Modal弹窗绑定方法
			var setModalOkFunction = function(func) {
				if (func != null && typeof(func) == "function") {
					$("#modalOkBtn").unbind('click');
					$("#modalOkBtn").click(function() {
						func();
					});
				}
			}
			var setModalCnlFunction = function(func) {
				$("#modalCnlBtn").unbind('click');
				$("#modalCnlBtn").click(function() {
					if (func != null && typeof(func) == "function") {
						func();
					}
					$("#modal").find(".modal-body").html("");
				});
			}
*/